package com.example.ch03myrealmhiro.config;

import com.example.ch03myrealmhiro.entity.User;
import com.example.ch03myrealmhiro.mapper.RPermissionsMapper;
import com.example.ch03myrealmhiro.mapper.URolesMapper;
import com.example.ch03myrealmhiro.mapper.UserMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.Set;

public class MyRealm extends AuthorizingRealm {
    @Resource
    private UserMapper userMapper;
    @Resource
    private URolesMapper uRolesMapper;
    @Resource
    private RPermissionsMapper rPermissionsMapper;

    @Override
    public String getName() {
       return  "myRealm";
    }

    //授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取用户名
        String username =(String) principals.iterator().next();
        //获取角色名
        Set<String> roles = uRolesMapper.selectRoles(username);
        //获取权限名
        Set<String> permissions = rPermissionsMapper.selctPermission(username);
        System.out.println("获取权限");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(permissions);

        return info;
    }

    //认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken token1= (UsernamePasswordToken)token;
        //从token中获取用户名
        String username = token1.getUsername();

        User user = userMapper.selectInfo(username);
        SimpleAuthenticationInfo info =
                new SimpleAuthenticationInfo(username,
                        user.getPassWord(),
                        ByteSource.Util.bytes(user.getSalt()),//得到盐
                        getName());

        return info;
    }
}
